package com.woniuxy.rabbitmqspringboot.configuration;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author zhangyong
 * @Date 2021/8/12 0012下午 3:05
 */
@Configuration
public class DeadConfiguration {

    private static final String DEAD_EXCHANGE = "dead_exchange";
    private static final String DEAD_ROUTING_KEY = "dead_key";

    /**
     * 延迟队列，业务交换机
     */
    @Bean
    public Queue delayQueue() {
        //指定queue的初始化参数
        Map<String, Object> map = new HashMap<>();

        //设置TTL时间
        map.put("x-message-ttl", 5000);

        //绑定死信交换机
        map.put("x-dead-letter-exchange", DEAD_EXCHANGE);

        //绑定死信路由:因为一个死信交换机可能绑定多个延迟队列，而每一个延迟队列业务不一样，当这些消息成为死信时就需要不同
        //死信消费者进行处理，此时死信交换机就可以根据绑定的死信路由将消息转发不同的死信消费进行处理
        map.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);

        return new Queue("delay_queue", true, false, false, map);
    }

    //延迟交换机
    @Bean
    public DirectExchange delayDirectExchange() {
        return new DirectExchange("delay_exchange");
    }

    //绑定交换机
    @Bean
    public Binding bindingDelayQueueToDelayDirectExchange(Queue delayQueue, DirectExchange delayDirectExchange) {
        return BindingBuilder.bind(delayQueue).to(delayDirectExchange).with("delay");
    }

    /**
     * 死信队列，业务交换机
     */
    //死信队列
    @Bean
    public Queue deadQueue() {
        return new Queue("dead_queue");
    }

    //死信交换机：就是普通交换机，知识用来专门处理死信，所以称之为死信交换机
    @Bean
    public DirectExchange deadDirectExchange() {
        return new DirectExchange(DEAD_EXCHANGE);
    }

    //绑定死信队列、死信交换机
    @Bean
    public Binding bindingDeadQueueToDeadDirectExchange(Queue deadQueue, DirectExchange deadDirectExchange) {
        return BindingBuilder.bind(deadQueue).to(deadDirectExchange).with(DEAD_ROUTING_KEY);
    }
}
